package v4

import (
	"fmt"
	"log"
	"os"
	"strconv"
)

const Usage = `
createBlockChain --address ADDRESS "创建区块链"
printChain "打印区块链"
getBalance --address ADDRESS "获取地址余额"
send --from ADDRESS --to ADDRESS --amount AMOUNT --miner ADDRESS "from给to转账amount,由miner记账"
`

type CLI struct {
}

func (cli *CLI) Run() {
	args := os.Args
	fmt.Println("接受到参数", args)
	length := len(args)
	if length < 2 {
		fmt.Println(Usage)
		return
	}
	//第二个参数
	cmd := args[1]
	switch cmd {
	case "createBlockChain":
		if length < 4 {
			fmt.Println(Usage)
			return
		}
		check := args[2]
		if check != "--address" {
			fmt.Println(Usage)
			fmt.Println("--address 不存在")
			return
		}
		cli.createBlockChain(args[3])
	case "printChain":
		cli.printChain()
	case "getBalance":
		if length < 4 {
			fmt.Println(Usage)
			return
		}
		check := args[2]
		if check != "--address" {
			fmt.Println(Usage)
			fmt.Println("--address 不存在")
			return
		}
		cli.getBalance(args[3])
	case "send":
		if length < 10 {
			fmt.Println(Usage)
			return
		}
		if args[2] != "--from" {
			fmt.Println(Usage)
			fmt.Println("--from 不存在")
			return
		}
		if args[4] != "--to" {
			fmt.Println(Usage)
			fmt.Println("--to 不存在")
			return
		}
		if args[6] != "--amount" {
			fmt.Println(Usage)
			fmt.Println("--amount 不存在")
			return
		}
		if args[8] != "--miner" {
			fmt.Println(Usage)
			fmt.Println("--miner 不存在")
			return
		}
		from := args[3]
		to := args[5]
		amount0 := args[7]
		amount, err := strconv.ParseFloat(amount0, 64)
		if err != nil {
			log.Fatal(err)
		}
		miner := args[9]
		cli.send(from, to, miner, amount)
	default:
		fmt.Println(Usage)
	}
}
